import React, { useEffect, useRef, useState } from 'react';
import { PostService } from '../API/PostService';
import { MyModal } from '../components/ModalComponent/MyModal';
import { PostFilter } from '../components/PostComponent/PostFilter';
import { PostForm } from '../components/PostComponent/PostForm';
import { PostList } from '../components/PostComponent/PostList';
import { CustomButton } from '../components/UI/Button/CustomButton';
import { CustomLoading } from '../components/UI/Loading/CustomLoading';
import { CustomPagination } from '../components/UI/Pagination/CustomPagination';
import { CustomSelect } from '../components/UI/Select/CustomSelect';
import { useFetching } from '../hooks/useFetching';
import { useObserver } from '../hooks/useObserver';
import { usePosts } from '../hooks/usePosts';
import { getPagesCount } from '../utils/getPagesCount';

export const Posts = () => {
  const [posts, setPosts] = useState([]);
  const [filter, setFilter] = useState({ sort: '', query: '' });
  const [modal, setModal] = useState(false);
  const [totalPages, setTotalPages] = useState(0);
  const [limitPosts, setLimitPosts] = useState(5);
  const [page, setPage] = useState(1);
  const lastElementOfPage = useRef();

  const searchedAndSortedPosts = usePosts(posts, filter.sort, filter.query);
  const [fetchPosts, isPostsLoading, postError] = useFetching(
    async (limitPosts, page) => {
      const response = await PostService.getAll(limitPosts, page);
      setPosts([...posts, ...(await response.json())]);

      const totalCount = response.headers.get('x-total-count');

      setTotalPages(getPagesCount(totalCount, limitPosts));
    }
  );

  useObserver(lastElementOfPage, page < totalPages, isPostsLoading, () => {
    setPage(page + 1);
  });

  useEffect(() => {
    fetchPosts(limitPosts, page);
  }, [page, limitPosts]);

  const createPost = (newPost) => {
    setPosts([...posts, newPost]);
    setModal(false);
  };

  const removePost = (post) => {
    setPosts(posts.filter((elem) => elem.id !== post.id));
  };

  const changePage = (page) => {
    setPage(page);
  };

  return (
    <div className="App">
      <CustomButton onClick={() => setModal(true)}>Создать пост</CustomButton>

      <MyModal isVisible={modal} setVisible={setModal}>
        <PostForm create={createPost} />
      </MyModal>

      <hr />

      <PostFilter filter={filter} setFilter={setFilter} />

      <CustomSelect 
        value={limitPosts}
        onChange={(value) => setLimitPosts(value)}
        defaultValue="Кол-во элементов на странице"
        options={[
          {value: 5, name: '5'},
          {value: 10, name: '10'},
          {value: 25, name: '25'},
          {value: -1, name: 'Показать все'},
        ]}
      />

      {postError && (
        <h1 className="header error">Произошла ошибка: {postError}</h1>
      )}

      <PostList
        remove={removePost}
        items={searchedAndSortedPosts}
        title={'Список постов'}
      />

      <div ref={lastElementOfPage} />

      {isPostsLoading && <CustomLoading />}
      <CustomPagination
        totalPages={totalPages}
        page={page}
        changePage={changePage}
      />
    </div>
  );
};
